<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.deptName" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item>
          <kt-button
            icon="fa fa-search"
            :label="$t('action.search')"
            type="primary"
            @click="findTreeData()"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            icon="fa fa-refresh" :label="$t('action.reset')"
            type="primary"
            @click="reset"
          />
        </el-form-item>
        <!-- <el-form-item>
          <kt-button icon="fa fa-plus" :label="$t('action.add')" type="primary" @click="handleAdd" />
        </el-form-item> -->
      </el-form>
    </div>
    <!--表格树内容栏-->
    <el-table
      :data="tableTreeDdata"
      stripe
      row-key="id"
      size="mini"
      style="width: 100%;"
      v-loading="loading"
      element-loading-text="$t('action.loading')"
      :header-cell-style="{ 'color': '#FFF','background-color': 'rgb(64, 158, 255)'}"
    >
      <el-table-column prop="id" header-align="center" align="center" width="80" label="ID"></el-table-column>
      <el-table-column prop="deptName" header-align="center" width="200" label="名称">
        <template slot-scope="scope">
          <div
            style="color:#2F4554;text-decoration:underline;cursor:pointer;"
            @click="findTreeData(scope.row.deptName)"
          >{{ scope.row.deptName }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="parent_name"
        header-align="center"
        align="center"
        width="200"
        label="上级机构"
      ></el-table-column>
      <el-table-column prop="sort" header-align="center" align="center" label="排序"></el-table-column>
      <el-table-column prop="createname" header-align="center" align="center" label="创建人"></el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间"
      ></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="185"
        :label="$t('action.operation')"
      >
        <template slot-scope="scope">
          <kt-button icon="fa fa-edit" :label="$t('action.edit')" @click="handleEdit(scope.row)" />
          <kt-button
            icon="fa fa-trash"
            :label="$t('action.delete')"
            type="danger"
            @click="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      width="40%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="submitForm()"
        label-width="80px"
        :size="size"
        style="text-align:left;"
      >
        <el-form-item label="名称" prop="deptName">
          <el-input v-model="dataForm.deptName" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" prop="parentName">
          <popup-tree-input
            :data="popupTreeData"
            :props="popupTreeProps"
            :prop="dataForm.parentName==null?'顶级机构':dataForm.parentName"
            :nodeKey="''+dataForm.pid"
            :currentChangeHandle="handleTreeSelectChange"
          ></popup-tree-input>
        </el-form-item>
        <el-form-item v-if="dataForm.type !== 2" label="排序编号" prop="sort">
          <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序编号"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click="submitForm()">{{$t('action.comfirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
import PopupTreeInput from "@/components/PopupTreeInput";
import FaIconTooltip from "@/components/FaIconTooltip";
import { format } from "@/utils/datetime";
export default {
  components: {
    PopupTreeInput,
    KtButton,
    TableTreeColumn,
    FaIconTooltip
  },
  data() {
    return {
      size: "small",
      loading: false,
      filters: {
        type:2
      },
      tableTreeDdata: [],
      dialogVisible: false,
      dataForm: {
        id: 0,
        deptName: "",
        pid: 0,
        parentName: "",
        sort: 0
      },
      dataRule: {
        deptName: [
          { required: true, message: "机构名称不能为空", trigger: "blur" }
        ],
        parentName: [
          { required: true, message: "上级机构不能为空", trigger: "change" }
        ]
      },
      popupTreeData: [],
      popupTreeProps: {
        label: "deptName",
        children: "children"
      }
    };
  },
  methods: {
    // 获取数据
    findTreeData: function(dept_name) {
      console.log(dept_name);
      if (this.utils.isNull(dept_name)) {
      } else {
        this.filters.deptName = dept_name;
      }

      var this_ = this;
      if (this_.utils.isNull(this_.filters.deptName)) {
        let params = Object.assign({}, this.filters);

        this.utils.request.findDeptTree(params, function(res) {
          if (res.code == "0000") {
            this_.tableTreeDdata = res.data;
            this_.popupTreeData = this_.getParentMenuTree(res.data);
          } else {
          }
        });
      } else {
        let params = Object.assign({}, this.filters);
        this.utils.request.queryDeptList(params, res => {
          this_.tableTreeDdata = res.data;
        });
      }
    },
    // 获取上级机构树
    getParentMenuTree: function(tableTreeDdata) {
      let parent = {
        id: 0,
        pid: 0,
        deptName: "顶级机构",
        children: tableTreeDdata
      };
      return [parent];
    },
    // 显示新增界面
    handleAdd: function() {
      this.dialogVisible = true;
      this.dataForm = {
        id: "",
        deptName: "",
        pid: "",
        parentName: "",
        sort: ""
      };
      if(this.$refs["dataForm"] != undefined){
        this.$refs["dataForm"].resetFields();
      }
    },
    reset: function() {
      // this.filters = {};
      if(this.$refs["filters"] != undefined){
        this.$refs["filters"].resetFields();
        this.filters.deptName = null;
      }
      this.findTreeData();
    },
    // 显示编辑界面
    handleEdit: function(row) {
      this.dialogVisible = true;
      this.dataForm = Object.assign({}, row);

      this.dataForm.parentName = row.parent_name;
      if (this.dataForm.pid == 0) {
        this.dataForm.parentName = "顶级机构";
      }
    },
    // 删除
    // handleDelete (row) {
    //   this.$confirm('确认删除选中记录吗？', '提示', {
    // 		type: 'warning'
    //   }).then(() => {
    //     debugger
    //       let params = this.getDeleteIds([], row)
    //       // data = this.getDeleteIds([], row)
    //       //let data = Object.assign({}, this.row)
    //       row.t="sysDept"
    //       row.ids=row.id
    //       this.utils.request.deleteUserInfo(row,this.deleteInfoBack)
    //   })
    // },
    // 批量删除
    handleDelete: function(row) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      }).then(() => {
        let params = this.getDeleteIds([], row);
        let ids = params.map(item => item.id).toString();
        row.t = "sysDept";
        row.ids = ids;
        this.utils.request.deleteDept(row, this.deleteInfoBack);
      });
    },
    //删除callback
    deleteInfoBack(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败, ", type: "error" });
      }
      this.findTreeData();
    },
    // 获取删除的包含子机构的id列表
    getDeleteIds(ids, row) {
      // debugger;
      ids.push({ id: row.id });
      if (row.children != null) {
        for (let i = 0, len = row.children.length; i < len; i++) {
          this.getDeleteIds(ids, row.children[i]);
        }
      }
      return ids;
    },
    // 机构树选中
    handleTreeSelectChange(data, node) {
      console.log(data);
      this.dataForm.pid = data.id;
      this.dataForm.parentName = data.deptName;
    },
    // 表单提交
    submitForm() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            delete params["level"];
            delete params["children"];
            // debugger
            if (params.parentName == "顶级机构") {
              params.pid = 0;
            }
            params.type = 2;
            if (this.utils.isNull(params.status)) {
              params.status = 0;
            }
            this.utils.request.editDeptInfo(params, this.editInfoBack);
          });
        }
      });
    },
    editInfoBack: function(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
        this.$refs["dataForm"].resetFields();
      } else {
        this.$message({ message: "操作失败", type: "error" });
      }
      this.dialogVisible = false;
      this.editLoading = false;
      this.findTreeData();
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    }
  },
  mounted() {
    this.findTreeData();
  }
};
</script>

<style scoped>
/deep/.el-table .cell,
.el-table th div,
.el-table--border td:first-child .cell,
.el-table--border th:first-child .cell {
  padding-left: 4px;
}
</style>